<template>
  <el-container>
    <el-header>PDF 文件管理</el-header>
    <el-upload
      class="upload-demo"
      action="http://localhost:3000/upload"
      :on-success="handleSuccess"
      :before-upload="beforeUpload"
    >
      <el-button size="small" type="primary">点击上传</el-button>
    </el-upload>
    <el-main>
      <el-table :data="files" stripe style="width: 100%">
        <el-table-column prop="name" label="文件名"></el-table-column>
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button type="primary" @click="previewFile(row.name)"
              >预览</el-button
            >
            <el-button type="danger" @click="deleteFile(row.name)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-main>
  </el-container>
</template>

<script setup>
import { ref, onMounted } from "vue";
import axios from "axios";

const files = ref([]);

const fetchFiles = async () => {
  const { data } = await axios.get("http://localhost:3000/files");
  files.value = data;
};

const previewFile = (filename) => {
  window.open(`http://localhost:3000/${filename}`);
};

const deleteFile = async (filename) => {
  await axios.delete(`http://localhost:3000/files/${filename}`);
  fetchFiles();
};

const handleSuccess = (response)=>{
  console.log("上传成功",response)
  forceUpdate(); // 手动强制组件更新
}
const beforeUpload = (file)=>{
  console.log("上传前",file)
}

const { forceUpdate } = useForceUpdate();

onMounted(fetchFiles);
</script>

<script>
  import { getCurrentInstance } from 'vue';

  export function useForceUpdate() {
    const instance = getCurrentInstance();
    if (!instance) {
      throw new Error('useForceUpdate must be called within a component');
    }

    const forceUpdate = () => {
      instance.proxy.$forceUpdate();
    };

    return { forceUpdate };
  }
</script>